# -*- coding:utf-8 -*-
from flask import request, jsonify, abort
from flask_cors import CORS
from com.zzh.dao_v2.cityDao import CityDao

from . import app

CORS(app, supports_credentials=True)


@app.route('/insertCity', methods=['POST'])
def insert_cityNoToken():
    """
    添加信息
    :return:
    """
    if not request.json:
        abort(400)
    info = {
        'cityName': request.json.get('cityName', ''),
        'cityZipcode': request.json.get('cityZipcode', ''),
        'provinceId': request.json.get('provinceId', '')
    }

    info = CityDao().insertCity(info)
    if info:
        return jsonify({"message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/findCityById', methods=['POST'])
def find_city_by_idNoToken():
    """
    根据ID查询
    :return:
    """
    if not request.json:
        abort(400)
    cityId = request.json.get('cityId', '')
    info = CityDao().findCityById(cityId)

    if info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/findCityByCondition', methods=['POST'])
def find_city_by_conditionNoToken():
    """
    条件查询
    :return:
    """
    if not request.json:
        abort(400)

    provinceId = request.json.get('provinceId', '')
    info = CityDao().findCityByCondition(provinceId=provinceId)

    if info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/deleteCityByIds', methods=['POST'])
def delete_city_by_idsNoToken():
    """
    根据ID删除，ID以数组形式传递
    :return:
    """
    if not request.json:
        abort(400)
    idArray = request.json.get('idArray', [0])

    info = CityDao().deleteCity(idArray)
    if info:
        return jsonify({"message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/updateCityById', methods=['POST'])
def update_city_by_idNoToken():
    """
    更新
    :return:
    """
    if not request.json:
        abort(400)
    try:
        cityId = request.json['cityId']
    except:
        return jsonify({"message": {"code": 0, "status": "请传入要修改信息的ID"}})
    oldInfo = CityDao().selectCity(cityId)
    info = {
        'cityId': request.json['cityId'],
        'cityName': request.json.get('cityName', oldInfo[1]),
        'cityZipcode': request.json.get('cityZipcode', oldInfo[2]),
        'provinceId': request.json.get('provinceId', oldInfo[3])
    }

    info = CityDao().updateCity(info)

    if info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})
